<?php
//模块名_控制名
class User_UserController extends Zend_Controller_Action
{
	public function preDispatch(){
		$this->tplDirectory = "user/user/";	//控制对应模板目录
	}
	
	public function indexAction(){
		$this->view->department =  User_Service_Department ::getAll();
		$this->view->position =  User_Service_Position ::getAll();
		echo Cff::renderTpl($this->tplDirectory."index.tpl","layout");	
    }
    
    public function listAction(){
    	
    	$page = $this->_request->getParam('page',1);
    	$pageSize = $this->_request->getParam('pageSize',20);
    	$ud_id = $this->_request->getParam('ud_id','');
    	$status = $this->_request->getParam('status','');
    	$login_id = $this->_request->getParam('login_id','');
    	$cond = array();
    	if(isset($ud_id) && $ud_id !=''){
    		$cond['ud_id'] = $ud_id;
    	}
    	if(isset($status) && $status !==''){
    		$cond['status'] = $status;
    	}
    	if(isset($login_id) && $login_id !=''){
    		$cond['login_id'] = $login_id;
    	}
    	
    	$order='user_id';
		$total = User_Service_User::getList($cond,'count');
		 
    	$userList = User_Service_User::getList($cond,'*','user_id',$page ,  $pageSize); 	
		$data=array('ask'=>0);
		if(!empty($userList)){
			$data=array(
				'total'=>$total,
				'result'=>$userList,
				'ask'=>1
			);
		}
		echo json_encode($data);
    }
    
    public function editAction(){
    	$user_id = $this->_request->getParam('user_id','');
    	$login_id = $this->_request->getParam('login_id','');
    	$passwd = $this->_request->getParam('passwd','');
    	
    	$name = $this->_request->getParam('name','');
    	$name_en = $this->_request->getParam('name_en','');
    	$email = $this->_request->getParam('email','');
    	
    	$telephone = $this->_request->getParam('telephone','');
    	$mobile_phone = $this->_request->getParam('mobile_phone','');
    	$status = $this->_request->getParam('status','');
    	$ud_id = $this->_request->getParam('ud_id','');
    	$up_id = $this->_request->getParam('up_id','');
    	
    	$row = array(
			'login_id' => $login_id,'name' => $name,
			'name_en' => $name_en,'email' => $email,
			'telephone' => $telephone,'mobile_phone' => $mobile_phone,
			'status' => $status,'ud_id' => $ud_id,
			'up_id' => $up_id,			
		);
        $error = array();
        $validateArr = array();
        $validateArr[] = array('name' => '姓名', 'value' => $row['name'], 'regex' => array('require', 'length[0,255]', ));
		$validateArr[] = array('name' => 'Login ID', 'value' => $row['login_id'], 'regex' => array('require', 'length[0,255]', ));
		$validateArr[] = array('name' => 'email', 'value' => $row['email'], 'regex' => array('require', 'email', ));
        $error = Common_Service_Validator::formValidator($validateArr);
        if(!empty($error)){
			$return=array(
				'ask'=>0,
				'error'=>$error,
			);
            die(Zend_Json::encode($return));
        }
		if(!empty($passwd)){
			$row['passwd'] = Common_Service_Password::getHash($passwd);
		}
		
		if($user_id){
			$row['last_update'] = date('Y-m-d H:i:s',time());
			$result = User_Service_User::update($row,$user_id);
		}else {
			$row['create_date'] = date('Y-m-d H:i:s',time());
			$result = User_Service_User::add($row);
		}
		
		if($result){
			$msg = array('ask'=>1);
    	}else{
    		$msg = array('ask'=>0);
    	}
		echo json_encode($msg);	
    }
    
    public function singleAction(){
    	$user_id = $this->_request->getParam('id','');
    	if($user_id){
    		$result = User_Service_User::getByUserId($user_id);
    		$data = array('ask'=>0);
    		if(count($result)){
				$data=array(
					'result'=>$result,
					'ask'=>1
				);
			}
    		echo json_encode($data);
    	}
    }
    
   
	
	public function modifypasswordAction() {	//跳转到修改密码页面
		$session = new Zend_Session_Namespace('userAuth');
		if(!$session->userID){header('location:/user/user/login'); exit;}
		echo Cff::renderTpl($this->tplDirectory."modifypassword.tpl","layout");
	}
	
	public function updatepasswordAction() {	//执行密码修改
		$session = new Zend_Session_Namespace('userAuth');
		if(!$session->userID){echo 'Invalid user'; exit;}

	 	$oldPasssword = trim($this->_request->getParam('oldPassword'));
		$password = trim($this->_request->getParam('password'));
		$rePassword = trim($this->_request->getParam('rePassword'));

        $adminuser =  User_Service_User::getByUserId($session->userID);
        $error = '';
		if(!$password || !$rePassword){
            $error = '请输入新密码';
        }
		if(!Common_Service_Password::comparePassword($oldPasssword, $adminuser['passwd'])){
            $error = '原密码错误';
        }
		if($password != $rePassword){
            $error = '新密码两次输入不一致';
        }
		if(strlen($password) < 6){
            $error = '密码长度不能小于 6 .';
        }
		if($oldPasssword == $password){
            $error = '新密码不能与原密码相同';
        }
        if($error != ''){
		    echo "<script>alert('" . $error ."');history.go(-1);</script>" ;
        }else{
        	$updateArray = array(
        		'passwd' => Common_Service_Password::getHash($password),
        		'passwd_update_date' => date('Y-m-d')
        	);
		    $info = User_Service_User::update($updateArray,$session->userID)?'Successfully modified.':'Modification failed.';
		    
		    if(!$session->username){//没有用户名，用户还没登录被强制修改密码	 
		    	$this->_redirect('/');
		    }else{	//已登录情况修改密码
            	echo "<script>alert('" . $info ."');history.go(-1);</script>" ;
            }
        }

	}
	
	public function rightsAction(){
    	$act = $this->_request->getParam('act','');
    	$id = $this->_request->getParam('id','');	//用户user表的user_id
    	
    	if($act != 'loadData'){
    		
    		//获取用户对应的权限
			$result = User_Service_RightMap::getRightByUserid($id);
			$rightIdArr  = $rightIdArr2 = array();
			foreach ($result as $key =>$val){
				$rightIdArr[] = $val['ur_id'];
			}
			
			//获取用户职位对应的默认权限
			$mapObj = new User_Service_PositionRightMap();
			$userInfo = User_Service_User::getByUserId($id);	//读取用户信息
			$positionRightsMap = $mapObj->getByPid($userInfo['up_id']);
			if(is_array($positionRightsMap) && $positionRightsMap){
				foreach ($positionRightsMap as $key =>$val){
					$rightIdArr2[] = $val['ur_id'];
				}
				$rightIdArr = array_merge($rightIdArr,$rightIdArr2);
				$rightIdArr = array_unique($rightIdArr);
			}

			$this->view->user_id = $id;
			$this->view->rightIdArr = implode(',',$rightIdArr);
    		echo Cff::renderTpl($this->tplDirectory."rights.tpl","layoutaction");
    		exit();
    	}
    	
    	$count = User_Service_Right::getByCond(array(),'count(*)','ur_id',0,0);
    	$data=array('ask'=>0);
    	if($count>0){
			$result = User_Service_Right::getByCond(array(),'*','ur_module',0,0);	
			$data=array(
				'count'=>$count,
				'result'=>$result,
				'ask'=>1
			);
		}
    	die(Zend_Json::encode($data));    	
    }
    
    public function loginAction() {
    	$session = new Zend_Session_Namespace('userAuth');
    	if($session->isLogin){
    		$this->_redirect('/');
    	}
    	$errMsg ='';
    	$this->view->errMsg = $errMsg;
    	echo $this->view->render('user/user/login.tpl');
    }
    
    public function saverightsAction(){
  		$delRow = $insertRow = $oldIdArr =  $positionRightArr = array();
    	$rights = $this->_request->getParam('rights',array());	//新提交的权限ID
    	$user_id = $this->_request->getParam('user_id','');
    	if(empty($user_id)){
    		exit('save error.');
    	}
    	
    	
    	
		$result = User_Service_RightMap::getRightByUserid($user_id);
		foreach ($result as $key => $val){
			$oldIdArr[] = $val['ur_id'];		//已有的权限ID
		}
		$delIdArr = array_diff($oldIdArr,$rights);
		$insertIdArr = array_diff($rights,$oldIdArr);
		
		//获取用户职位对应的默认权限
		$mapObj = new User_Service_PositionRightMap();
		$userInfo = User_Service_User::getByUserId($user_id);	//读取用户信息
		$positionRightsMap = $mapObj->getByPid($userInfo['up_id']);
		if(is_array($positionRightsMap) && $positionRightsMap){
			foreach ($positionRightsMap as $key =>$val){
				$positionRightArr[] = $val['ur_id'];
			}
		}
		
		foreach ($delIdArr as $key => $val){
			$cond = array('ur_id'=>$val,'user_id'=>$user_id,);
			$delRow[] = User_Service_RightMap::deleteBy($user_id,$val);
		}
		
		foreach ($insertIdArr as $key => $val){			
			if(in_array($val,$positionRightArr)){
				continue;
			}
			$cond = array('user_id'=>$user_id,'ur_id'=>$val);
			$insertRow[] = User_Service_RightMap::add($cond);
		}
		$data=array('ask'=>0);
		if(count($delRow) || count($insertRow)){
			$data=array('ask'=>1);
			die(Zend_Json::encode($data));	
		}
    }
	
    public function deleteAction(){
    	$user_id = $this->_request->getParam('id','');
    	if(!empty($user_id)){
    		$result = User_Service_User ::delete($ur_id);
    		if($result){
    			$msg = array('ask'=>1);
    		}else{
    			$msg = array('ask'=>0);
    		}
    		echo json_encode($msg);
    	}
    }

}